<template>
  <div>


    <div class="pd-10">
      <el-input style="width: 200px" placeholder="请输入名称" suffix-icon="el-icon-search" v-model="name"></el-input>

      <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
      <el-button class="ml-5" type="warning" @click="reset">重置</el-button>
    </div>

    <div class="mg-10">
      <el-button type="primary" @click="handleAdd">新增<i class="el-icon-circle-plus-outline ml-5"></i></el-button>

    </div>

    <el-table
        :data="tableData"
        border stripe

        :header-cell-style="{ background:'#eee',border: '1px solid #ccc' ,color: '#000'}"
        @selection-change="handleSelectionChange"
        row-key="id"
        :default-expand-all="false">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="name" label="课程名字" >
      </el-table-column>
      <el-table-column prop="coverSrc" label="课程封面"  >
        <template slot-scope="scope" v-if="scope.row.coverSrc">
          <el-empty description="课程封面" :image="scope.row.coverSrc"></el-empty>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="课程简要" >
      </el-table-column>
      <el-table-column prop="courseDetails" label="课程详情">
      </el-table-column>
      <el-table-column prop="study" label="看过人数" >
      </el-table-column>
      <el-table-column prop="size" label="时长">
      </el-table-column>
      <el-table-column prop="price" label="价格">
      </el-table-column>
      <el-table-column prop="viewsNumber" label="观看人数">
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope" >
          <el-button type="info" @click="handleAdd(scope.row)"  v-if="!scope.row.coverSrc">新增子课程<i class="el-icon-plus ml-5"></i></el-button>
          <el-button type="success" @click="handleEdit(scope.row)" >编辑<i class="el-icon-edit ml-5"></i></el-button>
          <el-popconfirm
              confirm-button-text='是的我确定'
              cancel-button-text='算了在想想'
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="handledelete(scope.row)"
              class="ml-5"
          >
            <el-button type="danger" slot="reference">删除<i class="el-icon-delete ml-5"></i></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="课程信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form"  label-width="80px" size="small">
        <el-form-item label="课程视频">
          <el-upload
              class="upload-demo"
              drag
              :limit="1"
              :action=" serverIp +'/files/upload'"
              multiple
              ref="uploadSrc"
              :on-success="uploadMusic">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程封面" >
          <el-upload
              :action="serverIp +'/files/upload'"
              :limit="1"
              :on-success="handleAvatarSuccess"
              list-type="picture-card"
              ref="uploadImg"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="form.coverImg" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="课程分类" >
          <el-select
              v-model="form.groupIds"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择课程分类">
            <el-option v-for="(item,index) in options" :key="index" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程标题" >
          <el-input v-model="form.name" autocomplete="off" ></el-input>
        </el-form-item>
        <el-form-item label="课程副标题" >
          <el-input v-model="form.title" type="text" show-word-limit  maxlength="30" autocomplete="off" ></el-input>
        </el-form-item>

        <el-form-item label="价格" >
          <el-input-number v-model="form.price" :precision="2" :step="0.1" ></el-input-number>
        </el-form-item>

        <el-form-item label="课程详情" >
          <el-input
              type="textarea"
              autosize
              placeholder="请输入内容"
              :autosize="{ minRows: 2, maxRows: 4}"
              v-model="form.courseDetails">
          </el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {serverIp} from "../../../public/config";

export default {
  name: "salescourse",
  data(){
    return{
      serverIp: serverIp,
      tableData: [], //分页数据
      total: 0, //总条数
      name: "", //搜索框用户名
      form: {
      }, //表格数据
      multipleSelection: [], //多选删除
      dialogFormVisible: false, //新增按钮
      options: [],  //课程组
      num: 1,
      dialogVisible: false,
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")):{},
    }
  },
  created() {
    this.load()
  },
  methods:{
    //分页请求
    load(){
      this.request.get("/salesCourse/group").then(res =>{
        if(res.code === "200"){
          this.tableData = res.data
          this.tableData.forEach((item)=>{
            item.children = item.children[0]===null?[]:item.children;
          })
          console.log("字=数据是",this.tableData)
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //分页方法
    handleSizeChange(pageSize) {
      this.pageSize=pageSize;
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load()
    },
    //重置搜索框
    reset(){
      this.name = "";
      this.load()
    },
    //新增子课程按钮
    handleAdd(item){
      this.dialogFormVisible = true;
      this.form = {}
      console.log("新增子课程",item)
      this.request.get("/salesCourseGroup").then(res =>{
        this.options = res.data
        this.form.groupIds.push(item.id)
      })


    },
    //确定新增
    save(){
      this.form.authorId = this.user.id;
      this.form.groupIds =  this.form.groupIds.filter(item=>{
        return item!=null;
      })
      this.request.post("/salesCourse", this.form).then(res=>{
        if(res.code ==="200"){
          this.$message.success(res.data)
          this.form ={}
          this.dialogFormVisible = false;
          this.load()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //编辑按钮
    handleEdit(row){
      this.form = row
      this.dialogFormVisible = true
      this.request.get("/salesCourseGroup").then(res =>{
        this.options = res.data
      })
    },
    //取消按钮
    cancel() {
      this.dialogFormVisible=false
      this.load()
    },
    //删除按钮
    handledelete(item){
      if(item.type===undefined){
        this.request.delete("/salesCourse/"+item.id).then(res=>{
          if(res.code === "200"){
            this.$message.success(res.data)
            this.load()
          }else {
            this.$message.error(res.msg)
          }
        })
      }else {
        this.request.delete("/salesCourseGroup/"+item.id).then(res=>{
          if(res.code === "200"){
            this.$message.success(res.data)
            this.load()
          }else {
            this.$message.error(res.msg)
          }
        })
      }



    },
    //批量删除多选
    handleSelectionChange(val){
      console.log(val)
      this.multipleSelection  = val
    },
    //点击批量删除
    delBatch(){
      let ids= this.multipleSelection.map(v => v.id)  //将数组内的id提取出来
      this.request.delete("/salesCourse/del/batch",{
        data: ids
      }).then(res=>{
        if(res.code === "200"){
          this.$message.success(res.data)
          this.load()
        }else {
          this.$message.error(res.msg)
        }
      })
    },
    //音乐文件上传成功后的回调
    uploadMusic(res, file, fileList){
      let name = file.name;
      let splice = name.split(" – ").length >1?name.split(" – "):name.split("-");
      console.log("splice",splice)
      this.form.name = splice[0]
      let musicauthor = splice[1]
      if(musicauthor.length >= 4 &&  musicauthor.substr( musicauthor.length - 4,musicauthor.length )===".mp3"){
        this.form.author = musicauthor.substr(0, splice[1].length - 4);
      }else {
        this.form.author = musicauthor;
      }
      this.form.audioSrc = res.data
      this.$forceUpdate()


    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    loadeddata() {
      // 需等音频加载完成，才能获取到音频的时长
      this.form.time = this.s_to_MS(this.$refs.Ref_audioPlayer.duration);
    },
    //图片上传方法
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw);
      this.form.coverSrc = res.data;
    },
    handlePictureCardPreview(file) {
      // this.form.goodsImgUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
    },
  }
}
</script>

<style>
.fontSize18{
  font-size: 18px;
}
.fontSize12{
  font-size: 15px;
}
</style>